﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using FU.Capstones.IMS.Web.Common;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.DataContracts;
using FU.Capstones.IMS.Web.Common.InventoryServiceProxy.EventArgs;
using FU.Capstones.IMS.Web.Silverlight.Models;
using Microsoft.Practices.Prism.Commands;
using Navigation.Silverlight;

namespace FU.Capstones.IMS.Web.Silverlight.ViewModels
{
    public class UserInfoViewModel : ViewModelBase
    {
        public UserInfoViewModel()
        {
            Model = new UserInfoModel();
            ((UserInfoModel)Model).ChangePasswordCompleted += ChangePasswordCompleted;
            ((UserInfoModel)Model).GetSingleEmployeeCompleted += GetSingleEmployeeCompleted;
            ((UserInfoModel)Model).GetAuthorizationCollectionCompleted += GetAuthorizationCollectionCompleted;

           
            ServiceCallCounter += ((UserInfoModel)Model).GetSingleEmployeeAsync(CurrentUser.EmployeeID);
            ServiceCallCounter += ((UserInfoModel)Model).GetAuthorizationCollectionAsync();
            Message = WebConstants.LoadingMessage;
            NewPasswordData = new NewPasswordData()
                                  {
                                      Username = CurrentUser.Username,
                                      Password = CurrentUser.Password,
                                      EmployeeID = CurrentUser.EmployeeID
                                  };
        }

        #region Completed Methods

        void ChangePasswordCompleted(object sender, FeedbackCompletedEventArgs e)
        {
            if (e.Error != null)
            {
                Message = e.Error.Message;
                SetMessageVisibility(false);
            }
            else
            {
                Message = e.Result.Message;
                SetMessageVisibility(e.Result.IsSuccessful);
                if (e.Result.IsSuccessful)
                {
                    CurrentUser.Password = NewPasswordData.NewPassword;
                    IMSIsolatedStorage.CurrentUser = CurrentUser;
                }
                else
                {
                    CurrentUser.Password = IMSIsolatedStorage.CurrentUser.Password;
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }

        void GetSingleEmployeeCompleted(object sender, SingleFeedbackCompletedEventArgs<Employee> e)
        {
            if (e.Error != null)
            {
                Message = e.Error.Message;
                SetMessageVisibility(false);
            }
            else
            {
                Message = e.Result.Message;
                SetMessageVisibility(e.Result.IsSuccessful);
                if (e.Result.IsSuccessful)
                {
                    MessageVisibility = Visibility.Collapsed;
                    Employee = e.Result.Data;
                    MappWithCollection();
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }

        void GetAuthorizationCollectionCompleted(object sender, CollectionFeedbackCompletedEventArgs<Authorization> e)
        {
            if (e.Error != null)
            {
                Message = e.Error.Message;
                SetMessageVisibility(false);
            }
            else
            {
                Message = e.Result.Message;
                SetMessageVisibility(e.Result.IsSuccessful);
                if (e.Result.IsSuccessful)
                {
                    AuthorizationCollection = e.Result.Data;
                    MappWithCollection();
                }
            }
            ServiceCallCounter -= WebConstants.MagicNumer;
        }

        #endregion

        #region SaveCommand

        private DelegateCommand<object> saveCommand;
        public DelegateCommand<object> SaveCommand
        {
            get
            {
                if (saveCommand == null)
                    saveCommand = new DelegateCommand<object>(DoSaveCommand);
                return saveCommand;
            }
        }

        private void DoSaveCommand(object obj)
        {
            newPasswordData.ValidateAll();
            if (!newPasswordData.HasErrors)
            {
                NewPasswordData.Password = NewPasswordData.CurrentPassword;
                ServiceCallCounter += ((UserInfoModel)Model).ChangePasswordAsync(newPasswordData);
            }
            else
            {
                Message = WebConstants.InvalidInputDataMessage;
                SetMessageVisibility(false);
            }
        }

        #endregion

        #region CancelCommand

        private DelegateCommand<object> cancelCommand;
        public DelegateCommand<object> CancelCommand
        {
            get
            {
                if (cancelCommand == null)
                    cancelCommand = new DelegateCommand<object>(DoCancelCommand);
                return cancelCommand;
            }
        }

        private void DoCancelCommand(object obj)
        {
            NavigationManager.NavigateTo(WebConstants.NavigationPages.EmployeeList);
        }

        #endregion

        #region ResetCommand

        private DelegateCommand<object> resetCommand;
        public DelegateCommand<object> ResetCommand
        {
            get
            {
                if (resetCommand == null)
                    resetCommand = new DelegateCommand<object>(DoResetCommand);
                return resetCommand;
            }
        }

        private void DoResetCommand(object obj)
        {
            
        }

        #endregion

        #region Binding Properties

        private Employee employee;
        public Employee Employee
        {
            get { return employee; }
            set
            {
                if(!ReferenceEquals(employee, value))
                {
                    employee = value;
                    RaisePropertyChanged(()=>Employee);
                }
            }
        }

        private NewPasswordData newPasswordData;
        public NewPasswordData NewPasswordData
        {
            get { return newPasswordData; }
            set
            {
                if(!ReferenceEquals(newPasswordData, value))
                {
                    newPasswordData = value;
                    RaisePropertyChanged(()=>NewPasswordData);
                }
            }
        }

        private ObservableCollection<Authorization> authorizationCollection;
        public ObservableCollection<Authorization> AuthorizationCollection
        {
            get { return authorizationCollection; }
            set
            {
                if (!ReferenceEquals(authorizationCollection, value))
                {
                    authorizationCollection = value;
                    RaisePropertyChanged(() => AuthorizationCollection);
                }
            }
        }

        private bool isCreateNew;
        public bool IsCreateNew
        {
            get { return isCreateNew; }
            set
            {
                if (isCreateNew != value)
                {
                    isCreateNew = value;
                    RaisePropertyChanged(() => IsCreateNew);
                }
            }
        }

        #endregion

        #region Implementation of INavigationAware

        public override void OnNavigate(object extraData)
        {
            
        }

        public override void OnLeave()
        {
            //throw new NotImplementedException();
        }

        #endregion

        private bool isMapped = false;

        private void MappWithCollection()
        {

            if (!isMapped)
            {
                
                if (Employee != null && Employee.AuthorizationCollection != null && AuthorizationCollection != null)
                {
                    isMapped = true;
                    int upper = Employee.AuthorizationCollection.Count;
                    for (int i = 0; i < upper; i++)
                    {
                        Authorization au = AuthorizationCollection.FirstOrDefault(x => x.AuthorizationID == Employee.AuthorizationCollection[i]);
                        if (au != null)
                            au.IsSelected = true;
                    }

                    AuthorizationCollection = new ObservableCollection<Authorization>(AuthorizationCollection.OrderByDescending(au => au.IsSelected));
                }
                
            }
        }
    }
}